package com.five.mobile.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.five.mobile.pojo.CarInfo;
import com.five.mobile.pojo.CarInfoDetails;
import com.five.mobile.service.CarService;
import com.five.pojo.vo.MobileProductListVo;
import com.five.service.ProductRpcService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CarServiceImpl implements CarService {

    @Resource
    private ProductRpcService productRpcService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    
    private final ObjectMapper objectMapper = new ObjectMapper();

    private static final String CAR_INFO_KEY = "car_info:";

    @Override
    public boolean addCarInfo(Long userId, CarInfo carInfo) {
        log.info("添加购物车：userId={}, carInfo={}", userId, carInfo);
        // 增加空值检查
        if (carInfo.getProductId() != null) {
            try {
                MobileProductListVo mobileProductListVo = productRpcService.listProductsById(carInfo.getProductId());
                if (mobileProductListVo != null) {
                    carInfo.setProductName(mobileProductListVo.getProductName());
                    carInfo.setProductPrice(mobileProductListVo.getPrice());
                    carInfo.setTotalPrice(new BigDecimal(carInfo.getQuantity()).multiply(mobileProductListVo.getPrice()));
                    carInfo.setImage(mobileProductListVo.getImage());
                    carInfo.setService(mobileProductListVo.getService());
                    log.info("填充后的carInfo: {}", carInfo);
                } else {
                    log.warn("未获取到商品信息，productId={}", carInfo.getProductId());
                }
            } catch (Exception e) {
                log.error("远程调用获取商品信息失败，productId={}", carInfo.getProductId(), e);
            }
        } else {
            log.warn("商品ID为空，无法获取商品信息");
        }
        
        if (userId != null && carInfo != null && carInfo.getId() != null) {
            try {
                String carInfoJson = objectMapper.writeValueAsString(carInfo);
                redisTemplate.opsForHash().put(CAR_INFO_KEY + userId,
                        carInfo.getId(),
                        carInfoJson);
                return true;
            } catch (JsonProcessingException e) {
                log.error("序列化CarInfo对象失败", e);
                return false;
            }
        }
        return false;
    }

    @Override
    public List<CarInfo> getCarInfo(Long userId) {
        if (userId == null) {
            return null;
        }
        List<Object> values = redisTemplate.opsForHash().values(CAR_INFO_KEY + userId);
        return values.stream()
                .filter(String.class::isInstance)
                .map(obj -> {
                    try {
                        return objectMapper.readValue((String) obj, CarInfo.class);
                    } catch (JsonProcessingException e) {
                        log.error("反序列化CarInfo对象失败", e);
                        return null;
                    }
                })
                .filter(carInfo -> carInfo != null)
                .collect(Collectors.toList());
    }

    @Override
    public CarInfoDetails getCarInfoDetails(Long userId, String id) {
        if (userId == null || id == null) {
            return null;
        }

        Object o = redisTemplate.opsForHash().get(CAR_INFO_KEY + userId, id);
        if (o instanceof String) {
            try {
                CarInfo carInfo = objectMapper.readValue((String) o, CarInfo.class);
                MobileProductListVo mobileProductListVo = productRpcService.listProductsById(carInfo.getProductId());

                // 添加空值检查
                if (mobileProductListVo == null) {
                    return null;
                }

                return CarInfoDetails.builder()
                        .id(carInfo.getProductId())
                        .productName(mobileProductListVo.getProductName())
                        .price(mobileProductListVo.getPrice())
                        .originalPrice(mobileProductListVo.getOriginalPrice())
                        .quantity(carInfo.getQuantity())
                        .totalPrice(new BigDecimal(carInfo.getQuantity()).multiply(mobileProductListVo.getPrice()))
                        .service(mobileProductListVo.getService())
                        .stockQuantity(mobileProductListVo.getStockQuantity())
                        .image(mobileProductListVo.getImage())
                        .build();
            } catch (JsonProcessingException e) {
                log.error("反序列化CarInfo对象失败", e);
                return null;
            }
        }

        return null;
    }

    @Override
    public void updateCarInfo(Long userId, CarInfo carInfo) {
        if (userId != null && carInfo != null && carInfo.getId() != null) {
            try {
                MobileProductListVo mobileProductListVo = productRpcService.listProductsById(carInfo.getProductId());
                if (mobileProductListVo != null) {
                    carInfo.setProductName(mobileProductListVo.getProductName());
                    carInfo.setProductPrice(mobileProductListVo.getPrice());
                    carInfo.setTotalPrice(new BigDecimal(carInfo.getQuantity()).multiply(mobileProductListVo.getPrice()));
                    carInfo.setImage(mobileProductListVo.getImage());
                    carInfo.setService(mobileProductListVo.getService());
                }
                String carInfoJson = objectMapper.writeValueAsString(carInfo);
                redisTemplate.opsForHash().put(CAR_INFO_KEY + userId,
                        carInfo.getId().toString(),
                        carInfoJson);
            } catch (JsonProcessingException e) {
                log.error("序列化CarInfo对象失败", e);
            }
        }
    }

    @Override
    public boolean deleteCarInfo(Long userId, String id) {
        if (userId == null || id == null) {
            return false;
        }

        Long delete = redisTemplate.opsForHash().delete(CAR_INFO_KEY + userId, id);
        return delete != null && delete > 0;
    }
}
